package com.edu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.eduservice.domain.EduSubject;
import com.edu.eduservice.domain.excel.SubjectData;
import com.edu.eduservice.service.EduSubjectService;
import com.edu.servicebase.exceptionhandler.MyException;

/**
 * @ClassName EasyExcelListener
 * @date 2022/9/15 15:42
 * @Version 1.0
 */
public class EasyExcelListener extends AnalysisEventListener<SubjectData> {


    //因为监听器不能交给spring容器 需要自己new 所以用构造方法注入
    public EduSubjectService eduSubjectService;

    public EasyExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){
            try {
                throw new MyException(20001,"excel数据为空");
            } catch (MyException e) {
                throw new RuntimeException(e);
            }
        }

        //一行行读取 一行包含了一级分类和二级分类
        
        //添加一级分类
        EduSubject onesubject = this.onesubject(eduSubjectService, subjectData.getOneSubjectName());
        //判断一级分类是否重复
        if(onesubject==null){
            EduSubject eduSubject=new EduSubject();
            eduSubject.setParentId("0");
            eduSubject.setTitle(subjectData.getOneSubjectName());
            this.eduSubjectService.save(eduSubject);
            onesubject=eduSubject;
        }
        
        //添加二级分类
        String one=onesubject.getId();
        EduSubject twosubject = this.twosubject(eduSubjectService, subjectData.getTwoSubjectName(), one);
        //判断二级分类是否重复
        if(twosubject==null){
            EduSubject eduSubject=new EduSubject();
            eduSubject.setParentId(one);
            eduSubject.setTitle(subjectData.getTwoSubjectName());
            this.eduSubjectService.save(eduSubject);
        }

    }

    //判断一级分类不重复添加
    public EduSubject onesubject(EduSubjectService subjectService,String name){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }

    //判断二级分类不重复添加
    public EduSubject twosubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject two = subjectService.getOne(wrapper);
        return two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
